﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace System.Work.ClientEngine.FPXH
{
    internal abstract class CommandFormat
    {
        public string AddressCode { get; }

        public CommandFormat(string addresscode)
        {
            AddressCode = addresscode;
        }

        public abstract byte[] MakeReadPacket(string[] address, int[] values, int slaveID = 1);
        public abstract byte[] MakeWritePacket(string[] address, int[] values, int slaveID = 1);
        public abstract EventArgs AnalysisReadPacket(string cmd, int count, int slaveID = 1);
        public abstract EventArgs AnalysisWritePacket(string cmd, int slaveID = 1);

        #region BCC校验

        protected string GetBCC(string code)
        {
            byte[] hexs = GetHexs(code);
            byte bcc = 0;
            for (int i = 0; i < hexs.Length; i++)
                bcc ^= Convert.ToByte(hexs[i].ToString(), 16);
            return Convert.ToString(bcc, 16).PadLeft(2, '0').ToUpper();
        }

        protected byte[] GetHexs(string code)
        {
            byte[] bytes = Encoding.ASCII.GetBytes(code);
            int len = bytes.Length;
            byte[] hexs = new byte[len];
            for (int i = 0; i < len; i++)
            {
                hexs[i] = Convert.ToByte(Convert.ToByte(bytes[i].ToString("X")));
            }
            return hexs;
        }
        #endregion
    }
}
